package top.maohh.study.demo.zookeeper;

import cn.hutool.core.util.RandomUtil;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import top.maohh.study.demo.zookeeper.config.ZookeeperConfig;

/**
 * 加入zk组
 *
 * @author maohh
 */
public class JoinGroup extends ConnectionWatcher {
    public void join(String groupName, String memberName, byte[] data) throws KeeperException, InterruptedException {
        String path = "/" + groupName + "/" + memberName;
        System.out.println("Will Create " + path + data.length);
        String createdPath = zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        System.out.println("Created " + createdPath);
    }

    public static void main(String[] args) throws Exception {
        JoinGroup joinGroup = new JoinGroup();
        joinGroup.connect(ZookeeperConfig.ZK_ADDRESS);
        Integer rand = RandomUtil.randomInt(1, 100);
        joinGroup.join(
                ZookeeperConfig.ZK_GROUP_NAME,
                ZookeeperConfig.ZK_GROUP_NAME + rand.toString(),
                "zk-tree".getBytes()
        );
// stay alive until process is killed or thread is interrupted
//        Thread.sleep(Long.MAX_VALUE);
    }
}
